﻿using iS3.DAL.SQL;
using iS3.DAL.Table;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iS3.DAL.SQLSERVER
{
    /// <summary>
    /// 数据操作语句类
    /// </summary>
     public class iS3SqlCreate
    {
        public iS3SqlCreate()
        {

        }
        public string TableName;
        public iS3DalBase dalHelper;

        /// <summary>
        /// 返回插入的字符串
        /// </summary>
        /// <returns>结果如:insert into tableName(id,Name,Value) values(@id,@Name,@Value)</returns>
        internal string GetInsertSql(iS3DataRow data,iS3DataTable table)
        {
            StringBuilder _TempSql = new StringBuilder();
            StringBuilder _TempSql2 = new StringBuilder();
            _TempSql.Append("insert into " + TableName + "(");
            _TempSql2.Append(") Values(");
            iS3DataCell primaryCell = data[table.Columns.FirstUnique.ColumnName];
            int groupID = iS3DataType.GetGroup(primaryCell.Struct.SqlType);
            string defaultValue = Convert.ToString(primaryCell.Struct.DefaultValue);
            iS3DataCell cell = null;
            for (int i = 0; i < data.Count; i++)
            {
                cell = data[i];
                if (cell.Struct.IsAutoIncrement)
                {
                    continue;//跳过自增列。
                }
                if (cell.State > 0)
                {
                    _TempSql.Append(iS3SqlFormat.Keyword(cell.ColumnName, iS3DataBaseType.MsSql) + ",");
                    _TempSql2.Append("@"+ cell.ColumnName + ",");
                    object value = cell.Value;
                    DbType dbType = iS3DataType.GetDbType(cell.Struct.SqlType.ToString(), iS3DataBaseType.MsSql);
                    dalHelper.AddParameters("@" + cell.ColumnName, value, dbType, cell.Struct.MaxSize, ParameterDirection.Input);
                }
            }
            string sql = _TempSql.ToString().TrimEnd(',') + _TempSql2.ToString().TrimEnd(',') + ")";
            if (primaryCell.Struct.IsAutoIncrement && groupID == 1)
            {
                if (!primaryCell.IsNullOrEmpty)
                    {
                        sql += string.Format(" select '{0}' as OutPutValue", primaryCell.Value);
                    }
                    if ( primaryCell.Struct.IsAutoIncrement)//非批量操作时
                    {
                        sql = "set identity_insert " + iS3SqlFormat.Keyword(TableName, iS3DataBaseType.MsSql) + " on " + sql + " set identity_insert " + iS3SqlFormat.Keyword(TableName, iS3DataBaseType.MsSql) + " off";
                    }
            }
            return sql;
        }
    }
}
